/**
 * Created by chengming on 18/5/27.
 * version 1.0
 */
const BaseJsonAdapter = require('../base/BaseJsonAdapter');
const ArticleHrefAdapter = require('../ArticleHrefAdapter');
const iconv = require("iconv-lite");
const vm = require('vm');
const request = require('request-promise');
const logger = require('../../conf/logger');
const querystring = require("querystring")
const cheerio = require('cheerio');
const urlTool = require('url');

/**
 * 北京互金网
 * @type {module.Bjp2p}
 */
module.exports = class WaiHuiGuanliJu extends ArticleHrefAdapter {

    initWinEnv(){
        global.window = {
            innerWidth:1232,
            innerHeight:632,
            screenX:11,
            screenY:22,
            screen:{
                width:1280,
                height:800
            }
        };

        global.document = {
            documentElement:{
                clientWidth:1217,
                clientHeight:550
            },
            body:{
                clientWidth:1217,
                clientHeight:1467
            },
            _cookie: [],

            get cookie(){
                return this._cookie;
            },

            set cookie(val){
                this._cookie.push(val);
            }
        };
    }

    async doRequest(){

        //初始化窗口属性
        this.initWinEnv();

        //创建全局cookie
        var jar = request.jar();

        //使用cookie
        const body = await super.doRequest();
        return body;
    }


    parseHtml(html, linkRule) {
        //将解析后的内容加载进解析器
        let $ = cheerio.load(html);

        let contents = [];
        let that = this;
        let rangeText = '';
        $(this.linkRule).each(function () {
            let jsStr = $(this).parent().parent().prev().html();
            jsStr = jsStr.replace(/replaceAll/g,'replace');
            vm.runInThisContext(jsStr);
            let title = _encodetitle;
            if(!/\([0-9]+\)/g.test(title) && !/（[0-9]+）/g.test(title)) {
                let href = '';
                if ($(this).is('a') && $(this).attr('href')) {
                    href = urlTool.resolve(that.requestUrl, $(this).attr('href'));
                }

                if (title.length != 0 || href.length != 0) {
                    contents.push({
                        title: title,
                        href: href
                    });
                    rangeText += title + href;
                }
            }


        });

        return {
            rangeText: rangeText,
            contents: contents
        };
    }


}
